import {
  getCompanyChangeLog,
  getCompanyById,
  getIdentityId,
  getCompanyApplyReviewResult,
  postCompanyApplyCheck,
  postIdentityCheck,
} from './service';
import { queryImageFromOss } from '@/services/user';
import { findIndex } from 'lodash';

export default {
  namespace: 'todoDetail',
  state: {
    companyInformation: {},
    reviewResult: {},
    companyChangeLog: {
      list: [],
      json: {},
    },
    userInformation:{},
  },

  effects: {
    *queryCompanyById({ payload }, { call, put }) {
      const response = yield call(getCompanyById, payload);
      //console.log(response.data)
      if (response.code === 1) {
        //console.log(response.data)
        let companyInformation = response.data;

        // 要查询的文件信息，用filter过滤，只查询拥有id的字段
        const requestFiles = [
          // logo
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: companyInformation.companyLogo,
            field: 'companyLogo',
          },
          // 营业执照
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: companyInformation.businessLicenceId,
            field: 'businessLicenceId',
          },
          // 法人身份证正面
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: companyInformation.legalPerFacePhoto,
            field: 'legalPerFacePhoto',
          },
          // 法人身份证反面
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: companyInformation.legalPerBackPhoto,
            field: 'legalPerBackPhoto',
          },
          // 授权证书
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: companyInformation.authorizationId,
            field: 'authorizationId',
          },
        ].filter(({ fileInfoId }) => !!fileInfoId);

        // 获取图片下载地址
        const filesResponse = yield call(queryImageFromOss, requestFiles);

        // 把获取到的图片信息比对一下确定每个对象对应哪个原来的字段，然后构造一个 原字段+Info 的新字段存储图片信息
        if (filesResponse.code === 1) {
          filesResponse.data.forEach(item => {
            const index = findIndex(requestFiles, { fileInfoId: item.fileInfoId });
            if (index !== -1) {
              companyInformation[`${requestFiles[index].field}Info`] = {
                uid: item.fileInfoId,
                name: item.fileName,
                status: 'done',
                url: item.downloadUrl,
                thumbUrl: item.downloadUrl,
              };
            }
          });
        }
        yield put({
          type: 'updateCompany',
          payload: companyInformation,
        });
        return Promise.resolve(response.data);
      }
      return Promise.reject(response.msg);
    },

    // 查询公司变更记录
    *queryCompanyChangeLog({ payload }, { call, put }) {
      const response = yield call(getCompanyChangeLog, payload);
      const {
        data,
        code,
      } = response;
      if (code === 1) {
        let jsonLike = {};
        data.forEach(({ fieldName, fieldNewValue }) => {
          jsonLike[fieldName] = fieldNewValue;
        });
        const requestFiles = [
          // logo
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: jsonLike.companyLogo,
            field: 'companyLogo',
          },
          // 营业执照
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: jsonLike.businessLicenceId,
            field: 'businessLicenceId',
          },
          // 法人身份证正面
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: jsonLike.legalPerFacePhoto,
            field: 'legalPerFacePhoto',
          },
          // 法人身份证反面
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: jsonLike.legalPerBackPhoto,
            field: 'legalPerBackPhoto',
          },
          // 授权证书
          {
            moduleCode: 'company',
            productLineId: 0,
            fileInfoId: jsonLike.authorizationId,
            field: 'authorizationId',
          },
        ].filter(({ fileInfoId }) => !!fileInfoId);
        // 获取图片下载地址
        if (requestFiles.length > 0) {
          const filesResponse = yield call(queryImageFromOss, requestFiles);

          // 把获取到的图片信息比对一下确定每个对象对应哪个原来的字段，然后构造一个 原字段+Info 的新字段存储图片信息
          if (filesResponse.code === 1) {
            filesResponse.data.forEach(item => {
              const index = findIndex(requestFiles, { fileInfoId: `${item.fileInfoId}` });
              if (index !== -1) {
                jsonLike[`${requestFiles[index].field}Info`] = {
                  uid: item.fileInfoId,
                  name: item.fileName,
                  status: 'done',
                  url: item.downloadUrl,
                  thumbUrl: item.downloadUrl,
                };
              }
            });
          }
        }

        yield put({
          type: 'updateChangeLog',
          payload: {
            list: data || [],
            json: jsonLike,
          },
        });
        return Promise.resolve();
      }
      return Promise.reject(response.msg);
    },

    // 获取用户身份认证信息
    *queryIdentityId({ payload }, { call, put }) {
      const response =  yield call(getIdentityId, payload);
      const { code, data } = response;
      if (code === 1) {
        let userInformation = response.data;
        const requestFiles = [
          // 法人身份证正面
          {
            productLineId: 0,
            fileInfoId: userInformation.picFrontId,
            field: 'picFrontId',
          },
          // 法人身份证反面
          {
            productLineId: 0,
            fileInfoId: userInformation.picBackId,
            field: 'picBackId',
          },
        ].filter(({ fileInfoId }) => !!fileInfoId);
        // 获取图片下载地址
        if (requestFiles.length > 0) {
          const filesResponse = yield call(queryImageFromOss, requestFiles);
          // 把获取到的图片信息比对一下确定每个对象对应哪个原来的字段，然后构造一个 原字段+Info 的新字段存储图片信息
          if (filesResponse.code === 1) {
            filesResponse.data.forEach(item => {
              const index = findIndex(requestFiles, { fileInfoId:  item.fileInfoId });
              if (index !== -1) {
                userInformation[`${requestFiles[index].field}Info`] = {
                  uid: item.fileInfoId,
                  name: item.fileName,
                  status: 'done',
                  url: item.downloadUrl,
                  thumbUrl: item.downloadUrl,
                };
              }
            });
          }
        }

        yield put({
          type: 'updateUserInformation',
          payload: userInformation,
        });
        return Promise.resolve(response.data);
      }
      return Promise.reject(response.msg);
    },
    // 查询公司 变更，创建 的审核结果
    *queryCompanyApplyReviewResult({ payload }, { call, put }) {
      const response = yield call(getCompanyApplyReviewResult, payload);
      if (response.code === 1) {
        yield put({
          type: 'upDateReviewResult',
          payload: response.data || {},
        });
        return Promise.resolve(response.data);
      }
      return Promise.reject(response.msg);
    },
    // 查询公司 实名认证 的审核结果
    *queryIdentityApplyReviewResult({ payload }, { call, put }) {
      const response = yield call(getIdentityId, payload);
      const { code, data, msg } = response;
      if (code === 1) {
        yield put({
          type: 'upDateReviewResult',
          payload: {
            ...data,
            verificationState: data.auditStatus,
            processRemark: data.auditRemark,
            updateTime: data.auditTime,
            updateBy: data.auditBy,
          } || {},
        });
        return Promise.resolve(data);
      }
      return Promise.reject(msg);
    },

    // code:BL003 - BL004提交审核结果
    *submitCompanyApplyCheckForm({ payload }, { call }) {
      const response = yield call(postCompanyApplyCheck, payload);
      if (response.code === 1) {
        return Promise.resolve();
      }
      return Promise.reject(response.msg);
    },
    // code:BL005提交审核结果
    *submitIdentityCheckForm({ payload }, { call }) {
      const response = yield call(postIdentityCheck, payload);
      if (response.code === 1) {
        return Promise.resolve();
      }
      return Promise.reject(response.msg);
    },
  },

  reducers: {
    updateCompany(state, { payload }) {
      state.companyInformation = payload;
    },
    updateChangeLog(state, { payload }) {
      state.companyChangeLog = payload;
    },
    upDateReviewResult(state, { payload }) {
      state.reviewResult = payload;
    },
    updateUserInformation(state, { payload }) {
      state.userInformation = payload;
    },
  },
};
